//
//  OrderManageVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/13.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "OrderManageVC.h"
#import "KwSegmentView.h"
#import "OrderStoreCell.h"
#import "OrderDetailVC.h"
#import "OrderCargoChooseVC.h"
#import "KwSegViewHelper.h"
#import "NwOrderRequest.h"
#import "OrderListModel.h"

@interface OrderManageVC ()<UITableViewDelegate,UITableViewDataSource>

//头部的条形title
@property(nonatomic,copy) NSArray *titleArr;

//当前选中的列表
@property (nonatomic,assign) NSInteger currtenNum;
@property (nonatomic,strong) UITableView *tabView;
//当前列表第几页
@property (nonatomic,assign) NSInteger currentPage;
//数据源
@property (nonatomic,strong) NSMutableArray *tableArray;

@end

@implementation OrderManageVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self configRefreshControl];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (![Singleton shareInstance].noRefresh) {
        [self.tabView.mj_header beginRefreshing];
    }
    [Singleton shareInstance].noRefresh = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNotification:) name:KwSegViewNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Config UI
- (void)configUI {
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"订单管理";
    [self setUpUI];
}

- (void)configRefreshControl {
    __weak typeof(self) weakSelf = self;
    self.tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.currentPage = 1;
        [weakSelf.tabView.mj_footer resetNoMoreData];
        [weakSelf loadingDataWithTag:1 showLoading:YES];
    }];
    [self.tabView.mj_header beginRefreshing];
    self.tabView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadingDataWithTag:0 showLoading:YES];
    }];
}

- (void)setUpUI
{
    //创建顶部菜单
    KwSegmentView *segView =[[KwSegmentView alloc]initWithBtnNames:self.titleArr];
    segView.btnNames = self.titleArr;
    segView.frame = CGRectMake(0, 0, self.view.width, 50);
    segView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:segView];
    segView.cancleBlock = ^(){
        [self.view endEditing:YES];
    };

    //创建列表
    self.tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    self.tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tabView.estimatedRowHeight = 40.0;
    self.tabView.rowHeight = UITableViewAutomaticDimension;
    self.tabView.delegate = self;
    self.tabView.dataSource = self;
    [self.view addSubview:self.tabView];
    [self.tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(segView.mas_bottom);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];

    if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency)
    {
        //创建底部按钮
        UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [confirmBtn setBackgroundColor:KwBlueColor];
        [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [confirmBtn setTitle:@"开始下单" forState:UIControlStateNormal];
        confirmBtn.titleLabel.font = KwFont(16.0);
        [confirmBtn addTarget:self action:@selector(startPlaceAnOrder) forControlEvents:UIControlEventTouchUpInside];
        confirmBtn.layer.masksToBounds = YES;
        confirmBtn.layer.cornerRadius = 5.0;
        [self.view addSubview:confirmBtn];
        [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(@-5);
            make.top.equalTo(self.tabView.mas_bottom).offset(1);
            make.left.equalTo(@5);
            make.right.equalTo(@-5);
        }];
    }
    else
    {
        [self.tabView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(@0);
        }];
    }

    UISwipeGestureRecognizer *swipeLeftGes = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doSomethingWithGestureRecognizer:)];
    [swipeLeftGes setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [self.tabView addGestureRecognizer:swipeLeftGes];

    UISwipeGestureRecognizer *swipeRightGes = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doSomethingWithGestureRecognizer:)];
    [swipeRightGes setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [self.tabView addGestureRecognizer:swipeRightGes];
}

#pragma mark - Data request
- (void)loadingDataWithTag:(NSInteger)tag showLoading:(BOOL)isShowLoading
{
    self.view.userInteractionEnabled = NO;
    __weak typeof(self) weakSelf = self;
    NwOrderRequest *request = [[NwOrderRequest alloc] init];
    switch (_currtenNum)
    {
        case 0:
        {
            //全部
            [request startRequestQueryAllOrdersWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:kPageSize orderStatus:@"" approvalType:@"" approverUserId:@""];
        }
            break;
        case 1:
        {
            //审批中
            [request startRequestQueryAllOrdersWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%zd",_currentPage] pageSize:[NSString stringWithFormat:@"%@",kPageSize] orderStatus:@"3,4,5,6,8" approvalType:@"0" approverUserId:@""];
        }
            break;
        case 2:
        {

            UserModel *user = [UserModel getUser];
            if ([user.userType integerValue] == UserTypeAgency)
            {
                //已完成
                [request startRequestQueryAllOrdersWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:[NSString stringWithFormat:@"%@",kPageSize] orderStatus:[NSString stringWithFormat:@"%ld",(long)OrderQueryStatusCompleted] approvalType:@"" approverUserId:@""];
            }
            else
            {
                //待我审批
                [request startRequestQueryAllOrdersWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:[NSString stringWithFormat:@"%@",kPageSize] orderStatus:[NSString stringWithFormat:@"%ld,2",(long)OrderQueryStatusToAudit] approvalType:@"" approverUserId:[Singleton shareInstance].userId];
  
            }

        }
            break;
        case 3:
        {
            UserModel *user = [UserModel getUser];
            if ([user.userType integerValue] == UserTypeAgency)
            {
                //已拒绝
                [request startRequestQueryAllOrdersWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:[NSString stringWithFormat:@"%@",kPageSize] orderStatus:@"" approvalType:@"1" approverUserId:@""];
            }
            else
            {
                //已完成
                [request startRequestQueryAllOrdersWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:[NSString stringWithFormat:@"%@",kPageSize] orderStatus:[NSString stringWithFormat:@"%ld",(long)OrderQueryStatusCompleted] approvalType:@"" approverUserId:@""];
            }

        }
            break;
        case 4:
        {
            //已拒绝
            [request startRequestQueryAllOrdersWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:[NSString stringWithFormat:@"%@",kPageSize] orderStatus:@"" approvalType:@"1" approverUserId:@""];
        }
            break;
        default:
            break;
    }

    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        [self stopRefresh];
        if (succ) {
            if (tag == 1) {
                [weakSelf.tableArray removeAllObjects];
            }
            if (result && result != nil)
            {
                NSDictionary *dic = result[@"orderList"];
                NSArray *arr = [OrderListModel arrayOfModelsFromDictionaries:dic[@"list"]];
                if ([dic[@"pageNo"] integerValue] ==_currentPage)
                {
                    _currentPage ++ ;//有下一页  show 加载按钮
                    [self.tableArray addObjectsFromArray:arr];
                    [self.tabView reloadData];
                }else if ([arr count] == 0)
                {
                    //没有下一页  hide 加载按钮
                    [weakSelf.tabView.mj_footer endRefreshingWithNoMoreData];
                    [self.tabView reloadData];

                }
//                else if([dic[@"count"] integerValue] >=_currentPage*10)
//                {
//                    //没有下一页  hide 加载按钮
//                    [weakSelf.tabView.mj_footer endRefreshingWithNoMoreData];
//                    [self.tableArray addObjectsFromArray:arr];
//                    [self.tabView reloadData];
//                }
            }

        }
        weakSelf.view.userInteractionEnabled = YES;
    }];
}

#pragma mark - Notification
- (void)getNotification:(NSNotification *)notification
{
    NSInteger seletIndex = [notification.userInfo[KwNotificationInfoKey_Index] integerValue];
    _currtenNum = seletIndex;
    [self.tabView.mj_header beginRefreshing];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"OrderStoreCell";
    OrderStoreCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (!cell)
    {
        cell = [[OrderStoreCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    OrderListModel *model = self.tableArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderListModel *model = self.tableArray[indexPath.row];
    OrderDetailVC *detaliVC = [[OrderDetailVC alloc] init];
    detaliVC.orderId = model.id;
    detaliVC.orderStatus = model.orderStatus;
    [self.navigationController pushViewController:detaliVC animated:YES];
}

#pragma mark - event response
- (void)doSomethingWithGestureRecognizer:(UISwipeGestureRecognizer *)swipeGes {
    if (swipeGes.direction == UISwipeGestureRecognizerDirectionLeft) {
        if (_currtenNum < self.titleArr.count-1 ) {
            _currtenNum = _currtenNum + 1;
        } else {
            return;
        }
    } else {
        if (_currtenNum <= 0) {
            return;
        } else {
            _currtenNum = _currtenNum - 1;
        }
    }
    KwSegViewHelper *kwHelper = [[KwSegViewHelper alloc] init];
    kwHelper.kwSegIndex = _currtenNum;
}

//开始下单
- (void)startPlaceAnOrder
{
    OrderCargoChooseVC *vc =[[OrderCargoChooseVC alloc] init];
    vc.type = VCTypeCommit;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - private method
- (void)stopRefresh {
    if ([self.tabView.mj_header isRefreshing]) {
        [self.tabView.mj_header endRefreshing];
    }
    if ([self.tabView.mj_footer isRefreshing]) {
        [self.tabView.mj_footer endRefreshing];
    }
}

#pragma mark - getter and setter
- (NSArray *)titleArr {
    if (!_titleArr) {
        if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency) {
            _titleArr = @[@"全部",@"审批中",@"交易完成",@"已拒绝"];
        } else {
            _titleArr = @[@"全部",@"审批中",@"待我审批",@"交易完成",@"已拒绝"];
        }
    }
    return _titleArr;
}

- (NSMutableArray *)tableArray {
    if (!_tableArray) {
        _tableArray = [NSMutableArray array];
    }
    return _tableArray;
}


@end
